﻿using System;
using System.Collections.Generic;
using System.Linq;
using Cjc.Calculation.ExpressionEngine;
using Cjc.Calculation.ExpressionEngine.Excel.Compiler;
using Cjc.Calculation.ExpressionEngine.Excel.Runtime.Binding;
using System.Linq.Expressions;
using Microsoft.Scripting;
using Microsoft.Scripting.Ast;
using System.Reflection;

namespace Cjc.Calculation.ExpressionEngine.Excel.Compiler
{
	public class WorksheetRewriter : ExpressionVisitor
	{
		private Worksheet worksheet;

		public bool IsOptimized { get; private set; }
		public List<Cell> Dependencies { get; private set; }

		public WorksheetRewriter( Worksheet worksheet )
		{
			this.worksheet = worksheet;
			Dependencies = new List<Cell>();
		}

		protected override Expression VisitMethodCall( MethodCallExpression node )
		{
			if ( node.Method != VariableRewriter.GetCellMethod ) return node;

			var formula = (Formula)( (ConstantExpression)node.Arguments[ 0 ] ).Value;
			var cell = worksheet[ formula ];
			Dependencies.Add( cell );
			IsOptimized = true;

			return Expression.Constant( cell );
		}
	}
}